package com.hopu.dy.controller;



import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import com.hopu.dy.pojo.R;
import com.hopu.dy.pojo.User;
import com.hopu.dy.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import jakarta.servlet.ServletContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Slf4j
@RestController   //提供对象
@RequestMapping("user")   //区别路径
public class UserController {

    /**
     * 邮件服务
     */
    @Resource
    JavaMailSender javaMailSender;

    @Resource
    ServletContext servletContext;   //应用层上下文对象(内存)，后台的全局变量

    @Resource
    private IUserService userService;

    /**
     * 获取验证码
     */
    @RequestMapping("captcha")
    public R getCaptcha(String email) throws MessagingException, UnsupportedEncodingException {
        System.out.println("正在发送验证码...");
        //TODO 实现发送邮件

        //生成验证码
        int captcha = (int) (Math.random() * 10000 + 900000);   //随机生产验证码，五位小数

        //将验证码保存在上下文对象中
        servletContext.setAttribute(email, captcha);    //存入邮箱和验证码

        // 创建一个邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();

        // 创建 MimeMessageHelper
        MimeMessageHelper helper = new MimeMessageHelper(message, false);

        // 发件人邮箱和名称
        helper.setFrom("15314154613@163.com", "免费阅读");

        // 收件人邮箱
        helper.setTo(email);  //接收传来的email

        // 邮件标题
        helper.setSubject("阅读验证码");

        // 邮件正文，第二个参数表示是否是HTML正文
        helper.setText(captcha+"", true);

        // 发送
        javaMailSender.send(message);

        System.out.println("验证码：" + captcha);

        return R.ok("发送成功");  //返回标准化 默认操作成功
    }

    /**
     * 登录注册
     * @param user
     * @return
     */
    @PostMapping("registerOrLogin")   //创建方法标签
    public  R registerOrLogin(@RequestBody User user) {  //接收对象,返回R类型返回值
        log.info("正在注册或登录{}...", user);
        userService.registerOrLogin(user);
        //生成token
        String token = JWT.create()
                .setPayload("email",user.getEmail())
                .setExpiresAt(DateUtil.date(DateTime.now().getTime()+1000*60*60*24*60))
                .setKey("lfkekgvrkvkr".getBytes())
                .sign();

        log.info("注册或登录成功");
        return R.ok("登录成功",token);
//        return R.ok("登录成功");
    }

    @GetMapping("getdata")
    public User getUserByEmail(String email) {
        return userService.getUserByEmail(email);
    }

    @PutMapping("update")
    public R update(@RequestBody User user) {
        userService.updateById(user);
        return R.ok("修改成功");
    }

}
